package org.example;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static String cookie = "acw_tc=0a47308c17439997036866646e003708c09864ccd8dc10ab6519ead64abef9; QCCSESSID=94e68b237b3fcbdc8f5f86d9b8; tfstk=ga7mi3wqki-XxH6KHT8bxUB3YAq8hjT64O39BFpa4LJSHx3A_FJGQLQvHsLqQVXGUKBAD1hfV9CEkZEXWVYX5FyLpyUdZsT67c3JiZpfa_OawIyaN8Hv5FyLenbFA7T1d4n_ui5zZCd9gxWwbLuyFBpw7K-ZU0ReUd8NQn8zzCdtQCo273Pk1LR27FWNajdsgp_NbayWA8upsORFrIxDL_qISVSxJnvFML0aLaAm3p52EVuwHqIfp_fYn21JlNWH9tUro9fNOG-lSYyHCafPuG5Sn78hZgIpmg2qSLQvsH8wqfuNZsJJ4N8U8YA54sINltci7I_AJhvBq5u6XU7pYMWm1W1yuCW6ANeIlK5NOwsp-rDBig5HrgoI4DJjJVOz6aosfnRWZpdKjsg2OMw0W7Vovct2NBvLZ7msfnRWZpFuZD960QOHp";
    public static String detailsURI = "";
    public static void main(String[] args) {
        // 初始化公共属性

        // 通过静态资源获取企业全名
        String enterpriseName = "杭州钢铁股份有限公司";
        String enterpriseKeyNo = "";
        String baseURI = "";


        // 根据名称，拼接网页
        /**
         * https://www.qcc.com/web/search?key=todo企业全称
         */
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建带验证参数的请求
            HttpGet validRequest = new HttpGet("https://www.qcc.com/web/search?key=" + enterpriseName);
            validRequest.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36");
            validRequest.setHeader("Cookie", cookie);
            // 发送验证后的请求
            CloseableHttpResponse validResponse = httpClient.execute(validRequest);
            String validHtml = EntityUtils.toString(validResponse.getEntity(), "UTF-8");
            // 使用正则表达式匹配KeyNo和Name
            Pattern pattern = Pattern.compile("\"KeyNo\":\"([^\"]*)\",\"Name\":\"([^\"]*)\"");
            Matcher matcher = pattern.matcher(validHtml);
            // 获取初始化数据
            Map<String, String> resultMap = new LinkedHashMap<>();
            while (matcher.find()) {
                resultMap.put(matcher.group(1), matcher.group(2));
            }
            {
                Iterator<Map.Entry<String, String>> iterator = resultMap.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, String> entry = iterator.next();
                    if (!entry.getValue().contains("\\u003Cem\\u003E")) {
                        iterator.remove();
                    }
                }
                for (Map.Entry<String, String> entry : resultMap.entrySet()) {
                    String cleanedValue = entry.getValue().replaceAll("\\\\u003C\\\\u002Fem\\\\u003E", "").replaceAll("\\\\u003Cem\\\\u003E", "");
                    entry.setValue(cleanedValue);
                }
            }
            //初始化格式KeyNo
            enterpriseKeyNo = "";
            // 再次校验，如果value值和查询值完全匹配，则获取到key值
            for (Map.Entry<String, String> entry : resultMap.entrySet()) {
                String cleanedValue = entry.getValue();
                if (cleanedValue.equals(enterpriseName)) {
                    enterpriseKeyNo = entry.getKey();
                }
            }
            //如果KeyNo不为空，则拼接详情页地址，否则返回空
            if (!enterpriseKeyNo.isEmpty() || enterpriseKeyNo != "") {
                detailsURI = "https://www.qcc.com/firm/" + enterpriseKeyNo + ".html";
                System.out.println(detailsURI);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //请求详情页
        try (CloseableHttpClient httpClient2 = HttpClients.createDefault()) {
            HttpGet detailsRequest = new HttpGet(detailsURI);
            detailsRequest.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36");
            detailsRequest.setHeader("Cookie", cookie);
            CloseableHttpResponse detailsResponse = httpClient2.execute(detailsRequest);
            String detailsHtml = EntityUtils.toString(detailsResponse.getEntity(), "UTF-8");
            System.out.println(detailsHtml);
            // 数据清洗，获取需要数据



        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}

